from django.contrib.sessions.models import Session
from django.http import JsonResponse
from django.utils import timezone
from django.contrib.auth import logout


class SingleSessionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            # 获取当前用户的活跃 Session
            sessions = Session.objects.filter(
                expire_date__gte=timezone.now(),
                session_key=request.session.session_key
            )
            if not sessions.exists():
                # 如果当前 Session 无效，强制注销用户
                logout(request)
                return JsonResponse({'status': 'error', 'message': 'Session expired'}, status=401)

        response = self.get_response(request)
        return response